package com.example.starter.webmvc.configure;

import cn.hutool.extra.spring.SpringUtil;
import com.example.starter.jackson.JavaTimeModule;
import com.example.starter.webmvc.handler.GlobalExceptionHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

/**
 * @author 王令
 * @since 2022/8/3 17:40
 */
@ImportAutoConfiguration(GlobalExceptionHandler.class)
@EnableConfigurationProperties({WebMvcProperties.class})
public class MvcAutoConfiguration {

    /**
     * 国际化文件配置
     */
    @Bean
    @ConditionalOnProperty(prefix = "com.example.mvc.i18n", name = "enabled", havingValue = "true")
    public MessageSource messageSource() {
        WebMvcProperties coreProperties = SpringUtil.getBean(WebMvcProperties.class);
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:" + coreProperties.getI18n().getBasename());
        return messageSource;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        mapper.registerModule(javaTimeModule);
        converter.setObjectMapper(mapper);
        return converter;
    }
}
